﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Command;
using Quizzer.Model;
using Quizzer.DataAccess;
using System.Collections.ObjectModel;

namespace Quizzer.ViewModel
{
    [Magic]
    public class QuestionViewModel : ViewModelBase
    {
        #region Constructor and MessageReceivers

        public QuestionViewModel()
        {
            Messenger.Default.Register<Test>(this, ReceiveMessage);
            Messenger.Default.Register<Attempt>(this, ReceiveMessage);
            Messenger.Default.Register<Question>(this, ReceiveMessage);
            
            GoToNextQuestion = new RelayCommand(() => ExecuteGoToNextQuestion(), () => (SelectedAnswer != null || !string.IsNullOrEmpty(CustomAnswer)));
        }

        // This message received only one time on beginning of the test
        private void ReceiveMessage(Attempt attempt)
        {
            _attempt = attempt;
        }

        // This message received only one time on beginning of the test
        private void ReceiveMessage(Test test)
        {
            _questions = QuestionRepository.GetQuestionsOfTest(test);
            _numberOfQuestions = TestRepository.GetNumberOfQuestionFoTest(test);

            ReceiveMessage(new Question());
        }

        // This message receiving on each question
        private void ReceiveMessage(Question q)
        {
            if (_currentQuestionNumber < _numberOfQuestions)        
            {                                                       
                _question = _questions[_currentQuestionNumber];     
                _currentQuestionNumber++;
            }
            else
            {
                GoToResults();
                return;
            }

            Text = _question.Text;
            Description = _question.Description;
            Image = _question.Image;

            if (_question.IsCheckBoxes == true)             // if there multiply choises in question
                SelectionMode = SelectionMode.Multiple;     // then selectionMode of ListView = Multiple
            else
                SelectionMode = SelectionMode.Single;

            if (_question.IsCustomAnswer == true)           // if there custom answer on the question
            {                                               // then hide ListView and show TextBox
                ListViewVisibility = Visibility.Collapsed;
                TextBoxVisibility = Visibility.Visible;
                CustomAnswer = "Enter your answer here";
            }
            else
            {
                ListViewVisibility = Visibility.Visible;
                TextBoxVisibility = Visibility.Collapsed;
            }

            AnswersList = AnswerRepository.GetAnswersOnQuestion(_question);
        }

        #endregion

        #region Fields

        private Question _question;     // current question (changes on each question)

        private static Attempt _attempt;    // current attempt (set only one time)
        private static int _currentQuestionNumber = 0;  // current question number (changes on each question)
        private static int _numberOfQuestions = 1;      // number of questions in test (set only one time)
        private static ObservableCollection<Question> _questions;   // question of the test (set only one time)
        
        #endregion

        #region Properties

        public ObservableCollection<Answer> AnswersList { get; set; } // answers on current question

        public string Text { get; set; }        // text of current question
        public string Description { get; set; } 
        public Image Image { get; set; }

        public Answer SelectedAnswer { get; set; }  // selected answer from List of Answer
        public string CustomAnswer { get; set; }    // custom Answer

        public Visibility ListViewVisibility { get; set; }
        public Visibility TextBoxVisibility { get; set; }
        public SelectionMode SelectionMode { get; set; }    // selection mode of listview

        #endregion

        #region Commands

        public ICommand GoToNextQuestion { get; private set; }
        private void ExecuteGoToNextQuestion()
        {
            QuestionResult qr = new QuestionResult();   // save question result
            qr.AttemptID = _attempt.Id;
            qr.QuestionID = _question.Id;

            if (_question.IsCustomAnswer == true)       
            {
                if (AnswersList[0].Text == CustomAnswer)    // if custom answer is correct than 
                    qr.AnswerWeight = 1;                    // AnswerWeight = 1
                else
                    qr.AnswerWeight = 0;
            }
            else
                qr.AnswerWeight = SelectedAnswer.Weight;    // else watch the selected answer in the listview

            if (qr.AnswerWeight >= 1)
                qr.IsPositive = true;
            else
                qr.IsPositive = false;

            QuestionResultRepository.Add(qr);

            //Messenger.Default.Send<ViewModelBase, MainViewModel>(new QuestionViewModel());
            Messenger.Default.Send<string, MainViewModel>("QuestionPage");
            Messenger.Default.Send<Question, QuestionViewModel>(_question);
        }

        private void GoToResults()
        {
            Messenger.Default.Send<string, MainViewModel>("TestResultPage");
            Messenger.Default.Send<Attempt, TestResultViewModel>(_attempt);

            Clean();
        }
	    #endregion

        private void Clean()
        {
            _attempt = null;
            _question = null;
            _currentQuestionNumber = 0;
            _numberOfQuestions = 0;
            _questions.Clear();
            SelectedAnswer = null;
            CustomAnswer = null;
            AnswersList = null;
            Text = "";
            Description = "";
            Image = null;
            SelectionMode = SelectionMode.Single;
        }
    }
}
